import axios from "axios";
import qs from "qs";
import store from "@/store";
import { API_BASE_URL } from "@/config";
import { redirectOCAuth,getWechatUser} from "@/api/index";
import router from "@/router";

// 创建axios实例
const fetch = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10 * 2000, // 请求超时时间
  headers: {
    // crossDomain: true, // 跨域
    "Content-Type": "application/x-www-form-urlencoded",
	"X-Requested-With":"xmlhttprequest",
    // "Content-Type": "application/json",
  }
});


window.fetch = fetch;

// request拦截器
fetch.interceptors.request.use(
  config => {
    // Do something before request is sent
    // const { token } = store.state;
	let token = sessionStorage.getItem("token")
    if (token) {
    //   // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
      config.headers.authorization = `${token}`; // eslint-disable-line no-param-reassign
    // config.headers.token = token; // eslint-disable-line no-param-reassign
    }
	store.commit("showLoading")
    if (
      config.data &&
      config.headers["Content-Type"] === "application/x-www-form-urlencoded"
    ) {
      config.data = qs.stringify(config.data); // eslint-disable-line no-param-reassign
    }
    return config;
  },
  error => {
	store.commit("hideLoading")
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// respone拦截器
fetch.interceptors.response.use(
  //code状态 0访问失败 1访问成功 3未绑定微信 4未关注公众号 5未获授权
  response => {
	store.commit("hideLoading")
    const {
      data: { code, msg, data }
    } = response;
	if(code == 0 ){
		throw new Error(msg);
		return msg
	}else if (code == 7){
    router.replace("/login?id=1")
  }
  else if (code == 1 ){
		return data
	}else if(code == 3 || code == 5){
		router.replace("/login")
	}else if (code == 4){
		router.replace("/followUs")
	}else if(code == 6){
		if(window.location.href.indexOf("code") == 0 || window.location.href.indexOf("code") <= 0){
			redirectOCAuth()
		}else{
			function getQueryString(name) {
				let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
				let r = window.location.search.substr(1).match(reg);
				if (r != null) {
				  return unescape(r[2]);
				} else {
				  return null;
				}
			}
				let code = getQueryString("code");
				// const res = await getWechatUser({code:code});
				getWechatUser({code:code}).then(res=>{
					window.location.search = "";
					// alert(window.location.search)
					sessionStorage.setItem("token",res.token)
				})
		}
		
	}
  },
  error => {
	store.commit("hideLoading")
    const {
      response: { data, status }
    } = error;
    console.log(error, data, status);
    return Promise.reject(error.response);
  }
);

export default fetch;
